<?php
/**
 * User: 269995848@qq.com
 * Date: 2019/2/28 16:06
 * 糙粒度实现一级接口
 */

namespace app\qqbot\service\behavior;


use app\lib\enum\QqBot;
use app\qqbot\service\behavior\achieve\MessageRoute;
use app\qqbot\service\behavior\Definition\KjBotDefinitionApi;
use app\qqbot\service\behavior\Definition\KjBotDefinitionBehaviorInterface;
use app\qqbot\service\src\MessageSender;
use think\facade\Log;


abstract class KjBotAchieveInterface implements KjBotDefinitionBehaviorInterface,KjBotDefinitionApi{

    protected $event;//监听数据
    protected $rout;
    protected $message;//支持消息队列

    public function __construct(){

        $this->event=$this->getData();
        $this->message=$this->handleData();
        $this->sendData();

    }
    abstract protected function index();

    final public function getData(){
        // TODO: Implement getData() method.
        if(!$event=json_decode(file_get_contents('php://input',true),true)){
            return null;
        }

        $data=redisObj()->get(QqBot::AGENT_LIST);
        foreach($data as $k => $v){
            if(isset($event['group_id']) && $k==$event['group_id']){
                $event['agent_id']=$v;
                return $event;
            }
        }
        exit();
    }

    final public function handleData(){
        // TODO: Implement handleData() method.
        return (new MessageRoute($this->event))->index();
    }

    final public function sendData(){
        // TODO: Implement sendData() method.

        $msgSender=new MessageSender();
        try{
            if(is_object($this->message)){
                $msgSender->send($this->message);

            }else{
                foreach($this->message as $v){
                    $msgSender->send($v);
                }
            }
        }catch(\Exception $e){
            Log::write("发送数据出错","error");
            //也可以改成自己的日志系统，我这是基于框架
        }
    }


}